import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 一级路由
import LoginView from '../views/LoginView.vue'
import LayoutView from '../views/LayoutView.vue'

// 二级路由
import DashboardView from '../views/DashboardView.vue'
import ArticleView from '../views/ArticleView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    component: LayoutView,
    children: [
      {
        path: '/',
        redirect: '/dashboard'
      },
      {
        path: 'dashboard',
        name: 'dashboard',
        component: DashboardView
      },
      {
        path: 'article',
        name: 'article',
        component: ArticleView
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
const white = ['/login']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  if (token) {
    if (white.includes(to.path)) {
      next(from.path)
    } else {
      next()
    }
  } else {
    if (white.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
